package com.demo.autotest.common.request;

import com.auth0.jwt.interfaces.DecodedJWT;
import com.demo.autotest.common.constant.RequestPath;
import com.demo.autotest.common.exception.DemoException;
import com.demo.autotest.common.exception.TokenNonException;
import com.demo.autotest.common.utils.JwtUtils;
import com.demo.autotest.database.domain.User;
import com.demo.autotest.database.mapper.UserMapper;
import com.demo.autotest.service.UserService;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;


public class LoginInterceptor implements HandlerInterceptor {
    /**
     * 在请求处理之前进行调用（Controller方法调用之前）
     * 基于URL实现的拦截器
     */
    @Resource
    private UserMapper userMapper;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String path = request.getServletPath();
        if (path.matches(RequestPath.LOGIN_PATH.value)) {
            // 平台登录注册接口 引擎获取token接口 测试截图预览 不用拦截
            return true;
        } else if (path.matches(RequestPath.ENGINE_PATH.value)){
            // 引擎拦截验证LMException
            String token = request.getHeader("token");
            if (token == null){
                throw new TokenNonException("token不能为空");
            }
            DecodedJWT jwt = JwtUtils.verifyToken(token);
            return true;
        } else {
            // 平台拦截验证
            String token = request.getHeader("token");
            if (token == null){
                throw new TokenNonException("token不能为空");
            }
            DecodedJWT jwt = JwtUtils.verifyToken(token);

            // 将请求的用户信息记录下来 给后续业务用
            request.getSession().setAttribute("userId", jwt.getClaim("userId").asString());
            request.getSession().setAttribute("account", jwt.getClaim("account").asString());
            // 当请求超过十分钟时 刷新新的Token 防过期
            Date createDate = jwt.getIssuedAt();
            if((new Date(System.currentTimeMillis() - 10*60*1000)).after(createDate)){
//                User user = userMapper.getUserById(jwt.getClaim("userId").asString());
//                String newToken = JwtUtils.createPlatformToken(user);
//                response.addHeader("token", token);
                User user = new User();
                user.setId(jwt.getClaim("userId").asString());
                user.setAccount(jwt.getClaim("account").asString());
                String newToken = JwtUtils.createPlatformToken(user);
                response.addHeader("token", newToken);
            }
            return true;
        }
    }
}
